const express = require('express');
const Product = require('../models/Product');
const { auth, admin } = require('../middleware/auth');

const router = express.Router();

// 获取所有产品
router.get('/', auth, async (req, res) => {
  try {
    const { page = 1, limit = 10, category } = req.query;
    const skip = (page - 1) * limit;
    
    let query = {};
    if (category) {
      query.category = category;
    }

    const products = await Product.find(query)
      .populate('createdBy', 'username')
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });

    const total = await Product.countDocuments(query);

    res.json({
      products,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取单个产品
router.get('/:id', auth, async (req, res) => {
  try {
    const product = await Product.findById(req.params.id).populate('createdBy', 'username');
    if (!product) {
      return res.status(404).json({ message: '产品不存在' });
    }
    res.json({ product });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建产品
router.post('/', auth, async (req, res) => {
  try {
    const { name, description, price, category, stock } = req.body;
    
    const product = new Product({
      name,
      description,
      price,
      category,
      stock,
      createdBy: req.user._id
    });

    await product.save();
    res.status(201).json({ message: '产品创建成功', product });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新产品
router.put('/:id', auth, async (req, res) => {
  try {
    const product = await Product.findById(req.params.id);
    if (!product) {
      return res.status(404).json({ message: '产品不存在' });
    }

    // 只有创建者或管理员可以修改
    if (product.createdBy.toString() !== req.user._id.toString() && req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }

    const updatedProduct = await Product.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );

    res.json({ message: '产品更新成功', product: updatedProduct });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除产品
router.delete('/:id', auth, async (req, res) => {
  try {
    const product = await Product.findById(req.params.id);
    if (!product) {
      return res.status(404).json({ message: '产品不存在' });
    }

    // 只有创建者或管理员可以删除
    if (product.createdBy.toString() !== req.user._id.toString() && req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }

    await Product.findByIdAndDelete(req.params.id);
    res.json({ message: '产品删除成功' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取产品分类
router.get('/categories/list', auth, async (req, res) => {
  try {
    const categories = await Product.distinct('category');
    res.json({ categories });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 